package com.webserver.controllers;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.vo.User;

import java.io.*;

/**
 * 处理用户相关业务
 */
public class UserController {
    private  static String usersDir="./users/";
    static {
        File userDir=new File(usersDir);
        if (!userDir.exists()){
            userDir.mkdirs();
        }
    }
    public void reg(HttpRequest request, HttpResponse response){
        System.out.println("开始处理用户注册！！！！！");
        //1通过request获取用户表单提交的数据
        //获取reg.html中用户名这个输入框的值
        //这里request.getParameter（）参数应当与页面上对于输入框的name属性的
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String nickname=request.getParameter("nickname");
        String ageStr=request.getParameter("age");
        System.out.println("username:"+username);
        System.out.println("password:"+password);
        System.out.println("nickname:"+nickname);
        System.out.println("ageStr:"+ageStr);
        int age=Integer.parseInt(ageStr);
        //2将该用户写入文件
        try(
                FileOutputStream fos=new FileOutputStream(usersDir+username+".obj");
                ObjectOutputStream oos=new ObjectOutputStream(fos);
                ){
                User user=new User(username,password,nickname,age);
                oos.writeObject(user);
            //3设置response响应登录结果页面
            File file=new File("./webapps/myweb/reg_success.html");
            response.setEntity(file);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
